package com.java.springboot.controller;

import org.apache.activemq.memory.buffer.MessageBuffer;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.jms.Queue;
import javax.jms.TextMessage;
import java.util.UUID;

@Controller
public class Activemqcontroller {


    @Autowired
    JmsMessagingTemplate jmsMessagingTemplate;



    @Autowired
    Queue queue;

    @RequestMapping(value = "send",method = RequestMethod.GET)
   /* @ResponseBody*/
    public String sendqueue(){
        String id = UUID.randomUUID().toString().substring(0,6);
        //消息幂等性产生原因：rabbitmq默认开启自动重试机制，因为网络异常，网络延迟等异常，rabbitmq就会自动重试直到异常结束，这就会产生消息幂等性问题
        //解决消息幂等性问题，设置messageId
        Message message = MessageBuilder.withBody(id.getBytes()).setContentType(MessageProperties.CONTENT_TYPE_JSON).setContentEncoding("UTF-8")
                .setMessageId(UUID.randomUUID().toString()).build();
        System.out.println(id);
        jmsMessagingTemplate.convertAndSend(queue,message);
        return "发送成功"+id;
    }

    @RequestMapping("receive")
    @JmsListener(destination = "${queue}")
    public String receive(TextMessage textMessage,Message message) throws  Exception{
        System.out.println(" ***  消费者收到消息  ***"+textMessage.getText());
        //获取messageId
        String messageId = message.getMessageProperties().getMessageId();
        String s = message.getBody().toString();
        return textMessage.getText();
    }

}
